package com.example.cloudpracticeplatform.service.impl;

import com.example.cloudpracticeplatform.entity.Enrollment;
import com.example.cloudpracticeplatform.mapper.EnrollmentMapper;
import com.example.cloudpracticeplatform.service.EnrollmentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class EnrollmentServiceImpl implements EnrollmentService {
    @Resource
    private EnrollmentMapper enrollmentMapper;

    @Override
    public boolean enrollCourse(Integer studentId, Integer courseId) {
        LocalDateTime now = LocalDateTime.now();
        
        // 检查是否存在对应的 studentId 和 courseId
        int exists = enrollmentMapper.existsEnrollment(studentId, courseId);
        
        if (exists > 0) {
            // 如果存在，则更新 enrollment_date
            return enrollmentMapper.updateEnrollmentDate(studentId, courseId, now) > 0;
        } else {
            // 如果不存在，则插入新记录
            return enrollmentMapper.insertEnrollment(studentId, courseId, now) > 0;
        }
    }

    @Override
    public Enrollment findEnrollment(Integer studentId, Integer courseId) {
        Enrollment enrollment = enrollmentMapper.findByStudentIdAndCourseId(studentId, courseId);
        return enrollment;
    }
}